package com.blockmeta.bbs.businesslibrary.net.retrofit;

import androidx.annotation.NonNull;

import com.blockmeta.bbs.baselibrary.BuildConfig;
import com.blockmeta.bbs.baselibrary.net.Host;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by author on 2018/11/5.
 */

public class RetrofitFactory {
    private static volatile Retrofit retrofit;
    private static volatile Retrofit rootRetrofit;

    @NonNull
    public static Retrofit getRetrofit() {
        if (retrofit == null) {
            synchronized (RetrofitFactory.class) {
                if (retrofit == null) {
                    retrofit = new Retrofit.Builder()
                                       .baseUrl(Host.BASE_URL)
                                       .client(BaseOKHttpClient.getIns().buildClient())
                                       .addConverterFactory(GsonConverterFactory.create())
                                       .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                                       .build();
                }
            }
        }
        return retrofit;
    }

    @NonNull
    public static Retrofit getRootRetrofit() {
        if (rootRetrofit == null) {
            synchronized (RetrofitFactory.class) {
                if (rootRetrofit == null) {
                    rootRetrofit = new Retrofit.Builder()
                            .baseUrl(Host.BASE_URL)
                            .client(BaseOKHttpClient.getIns().buildClient())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
        return rootRetrofit;
    }

    /**
     * 在登陆或退出登陆时，应调用此方法使客户端失效，再使用时就会重新初始化，避免登陆态没有因为登陆或退出登陆而发生变化
     */
    public static void invalidateRetrofitClient(){
        BaseOKHttpClient.invalidateOkHttpClient();
        retrofit = null;
        rootRetrofit = null;
    }

}
